package com.luck.easyfoodbatch.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.Constant;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.custom.RoundedImageView;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.mvp.mine.UploadImageModel;
import com.luck.easyfoodbatch.mvp.mine.UploadImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadSinglePresenter;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.OrderDetailM;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.mvp.order.RequestRefundModel;
import com.luck.easyfoodbatch.mvp.order.RequestRefundPresenter;
import com.luck.easyfoodbatch.mvp.order.RequestRefundView;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReturnGoodsActivity extends BaseActivity implements UploadImageView, RequestRefundView, RadioGroup.OnCheckedChangeListener {
    private final String TAG = "PersonalActivity";
    private List<LocalMedia> photoInfos = new ArrayList<>();

    @BindView(R.id.rabs)
    RadioGroup rabs;
    @BindView(R.id.rab1)
    RadioButton rab1;
    @BindView(R.id.rab2)
    RadioButton rab2;
    @BindView(R.id.tv_order_sn)
    TextView tv_order_sn;
    @BindView(R.id.tv_shop_name)
    TextView tv_shop_name;
    @BindView(R.id.iv_banner)
    ImageView iv_banner;
    @BindView(R.id.tv_shop_title)
    TextView tv_shop_title;
    @BindView(R.id.tv_spec)
    TextView tv_spec;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_due_date)
    TextView tv_due_date;
    @BindView(R.id.tv_num)
    TextView tv_num;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.et_number)
    EditText et_number;
    @BindView(R.id.tv_num_price)
    TextView tv_num_price;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.riv_avatar)
    RoundedImageView riv_avatar;
    @BindView(R.id.tv_return_money)
    TextView tv_return_money;
    @BindView(R.id.tv_ok)
    TextView tv_ok;
    @BindView(R.id.et_money)
    EditText et_money;
    @BindView(R.id.ll_input_money)
    LinearLayout ll_input_money;
    @BindView(R.id.ll_return_num)
    LinearLayout ll_return_num;
    private UploadImageModel imageModel;
    private String notice_img = "";
    private int refund_type = 1;
    private int is_include_freight = 1;
    private OrderDetailM.DataBean.OrderInfoBean infoBean;
    private String order_sn = "", shop_name = "", real_price = "", shop_price = "";
    private String price = "";
    private double product = 0;
    private RequestRefundModel refundModel;
    private double sum = 0.0;
    private String toChatUserName = "", nickname = "";
    private int status = 0;
    private int goods_num = 0;
    private double orderSumPrice = 0.0;
    private double v = 0.0;
    private double privilege = 0.0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_goods, "申请退款", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        infoBean = (OrderDetailM.DataBean.OrderInfoBean) getIntent().getSerializableExtra("serializable");
        rabs.setOnCheckedChangeListener(this);
        order_sn = getIntent().getStringExtra("order_sn");
        shop_name = getIntent().getStringExtra("shop_name");
        real_price = getIntent().getStringExtra("real_price");
        shop_price = getIntent().getStringExtra("shop_price");
        status = getIntent().getIntExtra("status", 0);
        goods_num = getIntent().getIntExtra("goods_num", 0);


        toChatUserName = getIntent().getStringExtra(Constant.EXTRA_USER_ID);
        nickname = getIntent().getStringExtra(Constant.EXTRA_NICK_ID);
        int due_date = infoBean.getDue_date();
        price = infoBean.getPrice();
        final int num = infoBean.getNum();
        String goods_name = infoBean.getGoods_name();
        String goods_thumb = infoBean.getGoods_thumb();
        if (!Tools.isNull(goods_thumb)) {
            String path = "";
            if (goods_thumb.startsWith("http")) {
                path = goods_thumb;
            } else {
                path = HttpUtil.IMG_THUMB_BASE_URL + goods_thumb;
            }
            Glide.with(getApplicationContext())
                    .load(path)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(iv_banner);
        } else {
            iv_banner.setImageResource(R.mipmap.loading_4b3);
        }
        if (!Tools.isNull(goods_name)) {
            tv_shop_title.setText(goods_name);
        } else {
            tv_shop_title.setText("");
        }
        tv_spec.setText(infoBean.getPropertyTags());
        if (!Tools.isNull(order_sn)) {
            tv_order_sn.setText("订单编号：" + order_sn);
        } else {
            tv_order_sn.setText("订单编号：");
        }
        if (!Tools.isNull(shop_name)) {
            tv_shop_name.setText(shop_name);
        } else {
            tv_shop_name.setText("");
        }
        if (!Tools.isNull(real_price)) {
            orderSumPrice = Double.parseDouble(real_price);
            tv_money.setText("￥" + real_price);
        } else {
            tv_money.setText("￥0");
        }
        if (!Tools.isNull(infoBean.getReal_price())) {
            tv_price.setText("￥" + infoBean.getReal_price());
        } else {
            tv_price.setText("￥0");
        }
        tv_due_date.setText(Tools.SubTime2(due_date + ""));
        tv_num.setText("x " + num);
        et_number.setText(num + "");
        if (!Tools.isNull(price)) {
            product = Double.parseDouble(price);
        }
        if (status == 1) {
            // 付款了 等待发货 只能退款
            ll_return_num.setVisibility(View.GONE);
            rab1.setVisibility(View.GONE);
            rab2.setChecked(true);
            refund_type = 2;
            et_number.setEnabled(false);
            ll_input_money.setVisibility(View.VISIBLE);
            et_money.setText(real_price);
            tv_return_money.setText("￥" + real_price);
        } else {
            ll_return_num.setVisibility(View.VISIBLE);
            rab1.setVisibility(View.VISIBLE);
            ll_input_money.setVisibility(View.GONE);
            et_number.setEnabled(true);
            refund_type = 1;
        }
        // real_price - voucher_price - privilege_price(总价 - 优惠券 - 折扣)/num*退款商品件数
//        if (!Tools.isNull(infoBean.getVoucher_price())) {
//            v = Double.parseDouble(infoBean.getVoucher_price());
//        }
        sum = (orderSumPrice - v) / goods_num * num;
        tv_num_price.setText("￥" + sum);
        tv_return_money.setText("￥" + sum);

        et_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!Tools.isNull(editable.toString())) {
                    int number = Integer.parseInt(editable.toString());
                    if (number > num) {
                        et_number.setText(num + "");
                        T.showToast(mContext, "退货数量不能大于商品数量");
                    } else {
                        // 订单总价 / 订单数量 * 退款数量
                        //sum = orderSumPrice / goods_num * number;
                        sum = (orderSumPrice - v) / goods_num * number;
                        tv_num_price.setText("￥" + sum);
                        tv_return_money.setText("￥" + sum);
                    }
                }
            }
        });

        et_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!Tools.isNull(editable.toString())) {
                    double money = Double.parseDouble(editable.toString());
                    if (money > orderSumPrice) {
                        tv_return_money.setText("￥" + orderSumPrice);
                        et_money.setText(orderSumPrice + "");
                        et_money.setSelection(et_money.getText().length());
                    } else {
                        tv_return_money.setText("￥" + editable.toString());
                    }
                }
            }
        });
    }

    @OnClick({R.id.riv_avatar, R.id.tv_ok, R.id.tv_phone})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.riv_avatar:
                FunctionConfig options = new FunctionConfig();
                options.setCompress(true);
                options.setSelectMode(FunctionConfig.MODE_SINGLE);
                PictureConfig.init(options);
                PictureConfig.getPictureConfig().openPhoto(ReturnGoodsActivity.this, resultCallback);
                break;
            case R.id.tv_ok:
                String note = et_content.getText().toString().trim();
                if (Tools.isNull(note)) {
                    note = "";
                }
                refundModel = new RequestRefundPresenter(this, mContext);
                String money = tv_return_money.getText().toString().trim().replaceAll("￥", "");
                if (!Tools.isNull(money)) {
                    double aDouble = Double.parseDouble(money);
                    if (aDouble <= 0) {
                        showToast("退款金额不能小于0");
                        return;
                    }

                }
                showProgressDialog(getString(R.string.app_loading));
                // sum 退款金额   shop_price
                switch (refund_type) {
                    case 1:
                        refundModel.requestRefund(infoBean.getInfo_id() + "", refund_type + "", note, notice_img, et_number.getText().toString().trim(), money + "");
                        break;
                    case 2:
                        // 仅退款 不传数量和价格
                        String price = "";
                        if (rab1.getVisibility() == View.VISIBLE && rab2.getVisibility() == View.VISIBLE) {
                            price = tv_return_money.getText().toString().trim().replaceAll("￥", "");
                        } else {
                            price = et_money.getText().toString().trim();
                        }
                        refundModel.requestRefund(infoBean.getInfo_id() + "", refund_type + "", note, notice_img, "", price);
                        break;
                }
                break;
            case R.id.tv_phone:
                bundle.putString(Constant.EXTRA_USER_ID, toChatUserName);
                bundle.putString(Constant.EXTRA_NICK_ID, nickname);
                startAct(ChatActivity.class, bundle);
                //showPhoneDialog();
                break;
        }
    }

    /**
     * 拨打电话
     */
    private void showPhoneDialog() {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        tv_title.setText("联系客服");
        btn_commit.setText("呼叫");
        tv_content.setText(HttpUtil.CALL_PHONE);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Tools.callPhone(HttpUtil.CALL_PHONE, mContext);
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    @Override
    public void uploadSuccess(UploadModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            List<String> data = model.getData();
            if (data != null && data.size() > 0) {
                notice_img = data.get(0);
            }
        } else {
            T.showToast(mContext, model.getMsg());
        }

    }

    @Override
    public void requestRefundSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                T.showToast(mContext, model.getMsg());
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {

    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rab1:
                refund_type = 1;
                ll_return_num.setVisibility(View.VISIBLE);
                ll_input_money.setVisibility(View.GONE);
                break;
            case R.id.rab2:
                refund_type = 2;
                ll_return_num.setVisibility(View.GONE);
                ll_input_money.setVisibility(View.VISIBLE);
                et_money.setText(real_price);
                break;
        }
    }

    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> list) {
            photoInfos = list;
            if (photoInfos != null || photoInfos.size() > 0) {
                LocalMedia media = photoInfos.get(0);
                File file;
                if (media.isCompressed()) {
                    file = new File(media.getCompressPath());
                } else {
                    file = new File(media.getPath());
                }

                Glide.with(getApplicationContext())
                        .load(file)
                        .asBitmap().centerCrop()
                        .placeholder(R.mipmap.camera)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(riv_avatar);
                try {
                    showProgressDialog("正在上传，请稍候……");
                    imageModel = new UploadSinglePresenter(ReturnGoodsActivity.this, mContext);
                    imageModel.uploads(0, file, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

}
